import { handleActions as createReducer } from 'redux-actions'
import { load_todo_success, add_todo_success, remove_todo_success, modify_todo_success, modify_actives_todo, clear_active_todo_success, modify_todo_edit_success, modify_active_success } from '../actions/todo.actions'

const initialState = {
    todos: [],
    filter: 'all'
}

export default createReducer({
    [load_todo_success]: (state, action) => ({ ...state, todos: action.payload }),
    [add_todo_success]: (state, action) => ({todos: [...state.todos, action.payload] }),
    [remove_todo_success]: (state, action) => {
        let res = action.payload
        let index = state.todos.findIndex(todo => todo.id === res)
        let todos = JSON.parse(JSON.stringify(state.todos))
        todos.splice(index, 1)
        return { ...state, todos }
    },
    [modify_todo_success]: (state, action) => {
        let res = action.payload
        let index = state.todos.findIndex(item => item.id === res.id)
        let todos = JSON.parse(JSON.stringify(state.todos))
        todos[index] = res
        return { ...state, todos }

    },
    [modify_actives_todo]: (state, action) => {
        return {
            ...state,
            filter: action.payload
        }
    },
    [clear_active_todo_success]: (state, action) => {
        let todos = JSON.parse(JSON.stringify(state.todos)).filter(item => !item.isCompleted)
        return {
            ...state, todos
        }
    },
    [modify_todo_edit_success]: (state, action) => {
        let todos = JSON.parse(JSON.stringify(state.todos))
        let index = state.todos.findIndex(item => item.id === action.payload.id)
        todos[index].isEditing = action.payload.isEditing
        return {
            ...state,
            todos
        }
    },
    [modify_active_success]: (state, action) => {
        let todos = JSON.parse(JSON.stringify(state.todos))
        let index = state.todos.findIndex(item => item.id === action.payload.id)
        todos[index].taskName = action.payload.taskName
        return {
            ...state,
            todos
        }
        
    }
}, initialState)

/**
 * 接收指令后处理数据
 */